package logic_setting_api

import (
	v1 "Sailor/app/Sailor-console-server/api/api_setting_api/v1"
	"Sailor/app/Sailor-console-server/internal/consts"
	"Sailor/app/Sailor-console-server/internal/dao"
	"Sailor/app/Sailor-console-server/internal/model/do"
	"context"
	"github.com/gogf/gf/v2/database/gdb"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gmeta"
	"github.com/google/uuid"
	"reflect"
)

func (s *sSettingApi) LogicSettingApiSync(ctx context.Context, req *v1.SettingApiSyncReq) (res *v1.SettingApiSyncRes, err error) {

	err = g.DB().Transaction(ctx, func(ctx context.Context, tx gdb.TX) error {
		_, err = dao.SysApi.Ctx(ctx).TX(tx).Unscoped().Where(dao.SysApi.Columns().DeletedAt, nil).Delete()
		if err != nil {
			return err
		}

		routes := consts.Server.GetRoutes()
		for _, item := range routes {
			handler := item.Handler
			if handler.Info.Type != nil && handler.Info.Type.NumIn() == 2 {
				uid, err := uuid.NewV7()
				if err != nil {
					g.Log().Error(ctx, err)
					return err
				}
				var objectReq = reflect.New(handler.Info.Type.In(1))
				_, err = dao.SysApi.Ctx(ctx).TX(tx).Insert(do.SysApi{
					Uuid:           uid.String(),
					ApiPath:        item.Route,
					ApiMethod:      item.Method,
					ApiDescription: gmeta.Get(objectReq, "summary").String(),
					ApiGroup:       gmeta.Get(objectReq, "tags").String(),
				})
				if err != nil {
					return err
				}
			}
		}
		return nil
	})
	if err != nil {
		g.Log().Error(ctx, err)
		return nil, gerror.New("同步失败")
	}

	return &v1.SettingApiSyncRes{}, nil
}
